package org.rulix.ogame.player.core.httpworker;

import java.util.List;
import java.util.concurrent.Callable;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.rulix.ogame.player.core.OgameCoreLogicImpl;
import org.rulix.ogame.player.core.OgameResponseHelper;
import org.rulix.ogame.player.core.OgameSession;
import org.rulix.ogame.player.core.http.OgameRequestFactory;

public class HttpLoginWorker implements Callable<Integer> {

	private String uni;
	private String login;
	private String password;
	private OgameCoreLogicImpl logic;
	
	public HttpLoginWorker(OgameCoreLogicImpl logic, String uni, String login, String password) {
		this.uni = uni;
		this.login = login;
		this.password = password;
		this.logic = logic;
	}
	
	@Override
	public Integer call() throws Exception {
		
		HttpClient client = logic.getHttpClient();
		OgameSession ogameSession = new OgameSession();
		ogameSession.setLogin(login);
		ogameSession.setPassword(password);
		ogameSession.setOgameServer(uni);
		
		HttpPost request = OgameRequestFactory.getLoginRequest(ogameSession);
		HttpResponse response = client.execute(request);
		
		//TODO: check response is not an error response.
		OgameResponseHelper orHelper = new OgameResponseHelper();
		boolean loggedIn = orHelper.isLoggedIn(response, ogameSession);
		
		if (loggedIn){
			DefaultHttpClient cl = (DefaultHttpClient)client;
			for (Cookie cookie : cl.getCookieStore().getCookies()) {
				if ( cookie.getName().equals("PHPSESSID") ){
					ogameSession.setSessionId(cookie.getValue());
				}
			}
			logic.setOgameSession(ogameSession);
			logic.changeStatusLoggedIn();
		}
		else {
			logic.changeStatusLoggedOut();
		}
		
		response.getEntity().getContent().close();
		return 0;
	}

}
